package com.bestv.search.common.util;

import com.bestv.search.common.model.*;
import com.bestv.search.common.model.uid.UID;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public final class XmlUtil {
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");

    public static List<Series> nodesToSeries(List<Element> nodes) {
        System.out.println("nodes to series : " + nodes.size());
        List<Series> seriesList = new ArrayList<Series>();
        Type type = new Type();
        type.setId(4l);
        type.setName("连续剧");
        type.setDescription("VOD(连续剧)");
        for (int i = 0; i < nodes.size(); ++i) {
            System.out.print("get num '" + i + "' series: ");
            Series series = new Series();
            try {
                Element e = nodes.get(i);
                String code = e.attributeValue("Code");
                String updateTime = e.attributeValue("UpdateTime");
                String name = e.selectSingleNode("Property[@Name='Name']").getText();
                String description = e.selectSingleNode("Property[@Name='Description']").getText();
                String startTime = e.selectSingleNode("Property[@Name='LicensingWindowStart']").getText();
                String endTime = e.selectSingleNode("Property[@Name='LicensingWindowEnd']").getText();
                // String tags =
                // e.selectSingleNode("Property[@Name='Tags']").getText();
                // String keywords =
                // e.selectSingleNode("Property[@Name='Keywords']").getText();

                series.setCode(code);
                series.setName(name);
                series.setType(type);
                series.setDescription(description);
                series.setUpdateTime(sdf.parse(updateTime));
                series.setStartTime(sdf.parse(startTime));
                series.setEndTime(sdf.parse(endTime));
                // series.setTags(tags);
                series.setNamePY(ChineseCharToEn.getAllFirstLetter(name));
                // series.setKeywords(keywords);
                seriesList.add(series);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return seriesList;
    }

    public static List<Info> nodesToPrograms(List<Element> nodes) {
        System.out.println("nodes size : " + nodes.size());
        List<Info> programList = new ArrayList<Info>();
        Type type = new Type();
        type.setId(3L);
        type.setName("VOD");
        type.setDescription("VOD");
        for (int i = 0; i < nodes.size(); ++i) {
            Program program = new Program();
            try {
                Element e = nodes.get(i);
                String code = e.attributeValue("Code");
                String updateTime = e.attributeValue("UpdateTime");
                String name = e.selectSingleNode("Property[@Name='Name']").getText();
                String description = e.selectSingleNode("Property[@Name='Description']").getText();
                String startTime = e.selectSingleNode("Property[@Name='LicensingWindowStart']") == null ? null : e
                        .selectSingleNode("Property[@Name='LicensingWindowStart']").getText();
                String endTime = e.selectSingleNode("Property[@Name='LicensingWindowEnd']") == null ? null : e
                        .selectSingleNode("Property[@Name='LicensingWindowEnd']").getText();
                String actors = e.selectSingleNode("Property[@Name='ActorDisplay']").getText();
                String directors = e.selectSingleNode("Property[@Name='WriterDisplay']").getText();

                String p_type = e.selectSingleNode("Property[@Name='Type']").getText();
                String tag = e.selectSingleNode("Property[@Name='Tags']").getText();
                String keyword = e.selectSingleNode("Property[@Name='Keywords']").getText();
                String seriesFlag = e.selectSingleNode("Property[@Name='SeriesFlag']").getText();
                program.setP_type(p_type);
                program.setCode(code);
                program.setName(name);
                // program.setNamePY(ChineseCharToEn.getAllFirstLetter(name));
                program.setType(type);
                program.setDescription(description);
                // program.setUpdateTime(sdf.parse(updateTime));
                if (startTime != null)
                    program.setStartTime(sdf.parse(startTime));
                if (endTime != null)
                    program.setEndTime(sdf.parse(endTime));
                program.setIsSeries(!"0".equals(seriesFlag));
                program.setActors(actors);
                program.setDirectors(directors);
                Date ut = null;
                try {
                    ut = DateUtil.convertStringToDate("yyyyMMddhhmmss", updateTime);
                } catch (ParseException e1) {
                    e1.printStackTrace();
                }
                program.setUpdateTime(ut);
                Date d = new Date();
                program.setUpdateTimeForIndex(d);
                String[] keywords = keyword.split("[\\[\\]\\-,;、 ]+");
                Set<Keyword> keys = new HashSet<Keyword>();
                for (String key : keywords) {
                    if (key == null || "".equals(key))
                        continue;
                    Keyword k = new Keyword();
                    k.setKeyword(key);
                    keys.add(k);
                }
                program.setKeywords(keys);

                Set<Tag> ts = new HashSet<Tag>();
                String[] tags = tag.split("[\\[\\]\\-,;、 ]+");
                for (String tg : tags) {
                    if (tg == null || "".equals(tg))
                        continue;
                    Tag t = new Tag();
                    t.setTag(tg);
                    ts.add(t);
                }
                program.setTags(ts);
                program.setUpdateFlag(0);
                program.setUpdateTimeMillis(Long.valueOf(DateUtil.convertDateToString("yyyyMMddHHmm", ut)));
                program.setId(new Long(UID.getUID(program)));
                programList.add(program);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return programList;
    }

    @SuppressWarnings("unchecked")
    public static String getFilenamesByCode(File[] fileList, String type, String code) {
        String filenames = null;
        Document doc = null;
        for (File file : fileList) {
            try {
                doc = loadXMLFile(file);
            } catch (FileNotFoundException e) {
                System.out.println(file.getName() + " is not exist!");
                e.printStackTrace();
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            // List<Element> list = doc.selectNodes("//Object[@ElementType='" +
            // type + "' and @Action!='SYNC']");
            List<Element> list = doc.selectNodes("//Object[@ElementType='" + type + "' and @Code='" + code + "']");
            if (list.size() > 0) {
                System.out.println(file.getName());
                filenames += file.getName() + ",";
            }
        }
        return filenames;
    }

    @SuppressWarnings("unchecked")
    public static List<Element> getAllNodesWithProgramAttribute(File[] fileList, String type) {
        List<Element> elements = new ArrayList<Element>();
        List<Element> list = new ArrayList<Element>();
        Document doc = null;
        for (File file : fileList) {
            try {
                doc = loadXMLFile(file);
            } catch (FileNotFoundException e) {
                System.out.println(file.getName() + " is not exist!");
                e.printStackTrace();
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            list = doc.selectNodes("//Object[@ElementType='" + type + "' and @Action='SYNC']");
            // for(int i = 0; i < list.size(); ++i)
            // {
            // Element e = list.get(i);
            // try
            // {
            // String startTime =
            // e.selectSingleNode("Property[@Name='LicensingWindowStart']").getText();
            // }catch(Exception el)
            // {
            // el.printStackTrace();
            // System.out.println(file.getName());
            // System.exit(0);
            // }
            // }
            // list =
            // doc.selectNodes("//Object[@ElementType='Program' and @Action='SYNC']");
            if (list != null && list.size() > 0)
                elements.addAll(list);
        }
        return elements;
    }

    public static void printNodes(List<Element> list) {
        try {
            Writer out = new OutputStreamWriter(System.out, "gb2312");
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writerConsole = new XMLWriter(out, format);
            writerConsole.write("" + list.size());
            for (int i = 0; i < list.size(); ++i) {
                Element e = list.get(i);
                writerConsole.write(e);
            }
            writerConsole.flush();
            writerConsole.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    public static Document loadXMLByFilename(String filename) throws FileNotFoundException, DocumentException {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(new FileInputStream(filename));
        return doc;
    }

    public static Document loadXMLFile(File xmlfile) throws FileNotFoundException, DocumentException {
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(new FileInputStream(xmlfile));
        } catch (Exception e) {
            System.out.println(xmlfile.getName());
            e.printStackTrace();
            System.exit(0);
        }
        return doc;
    }

    public static void printDoc(Document doc) throws IOException {
        Writer out = new OutputStreamWriter(System.out, "gb2312");
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(doc);
        out.flush();
        out.close();
    }

    public Document loadXml(String s) {
        return null;
    }

    public void storeDoc(Document doc, String filename) throws IOException {
        Writer out = new OutputStreamWriter(new FileOutputStream(filename), "utf-8");
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(doc);
        out.close();
    }
}
